package com.kobi.tapeRecorder;

import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;

public class MainList extends Activity {
	public ListView listView;
	public ScrollView mScrollView;
	public TextView mTextView;
	private Context context;
	private List<Model> listDir;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_list);

		listView = (ListView) findViewById(R.id.mylist);
		mScrollView = (ScrollView) findViewById(R.id.ScrollView01);
        mTextView = (TextView) findViewById(R.id.txtNoRecords);
        
        context = this;
	}

	@Override
	protected void onResume() {
		String filepath = Environment.getExternalStorageDirectory().getPath();
    	final File file = new File(filepath, RecordService.FILE_DIRECTORY);
				
		if (!file.exists()) {
			file.mkdirs();
		}
		
		listDir = ListDir2(file);
		
		if (listDir.isEmpty())
		{
			mTextView.setVisibility(TextView.VISIBLE);
			mScrollView.setVisibility(ScrollView.GONE);
		}
		else
		{
			mTextView.setVisibility(TextView.GONE);
			mScrollView.setVisibility(ScrollView.VISIBLE);
		}
		
		final MyCallsAdapter adapter = new MyCallsAdapter(this, listDir);
    	
		listView.setOnItemClickListener(new OnItemClickListener() {

			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				showPromotionPieceDialog(listDir.get(position)
						.getCallName(), position);
			}
		});
		
		adapter.sort(new Comparator<Model>() {

			public int compare(Model arg0, Model arg1) {
				Long date1 = Long.valueOf(arg0.getCallName().substring(1, 15));
				Long date2 = Long.valueOf(arg1.getCallName().substring(1, 15));
				return (date1 > date2 ? -1 : (date1 == date2 ? 0 : 1));
			}

		});
    	
		listView.setAdapter(adapter);		
		
		super.onResume();
	}
	
	/**
     * shows dialog of promotion tools
     */
    public void showPromotionPieceDialog(final String fileName, final int position)
    {
    	
    	final CharSequence[] items = {context.getString(R.string.options_delete), context.getString(R.string.confirm_play), context.getString(R.string.confirm_send)};
    	
    	new AlertDialog.Builder (context)
    	.setTitle(R.string.options_title)
    	.setItems(items, new DialogInterface.OnClickListener() {
    	    public void onClick(DialogInterface dialog, int item) {
    	        if (item == 0)
    	    	{
    	        	DeleteRecord(fileName, position);
    	    	}
    	    	else if (item == 1)
    	    	{
    	    		//startPlay(fileName);
    	    		startPlayExternal(fileName);
    	    	}
    	    	else if (item == 2)
    	    	{
    	    		sendMail(fileName);
    	    	}
    	    	
    	    }
    	})
    	.show();
    	
    	
    }
    
    private void DeleteRecord(final String fileName, final int position)
    {
    	new AlertDialog.Builder (context)
        .setTitle (R.string.confirm_delete_title)
        .setMessage (R.string.confirm_delete_text)
        .setPositiveButton (R.string.confirm_delete_yes, new DialogInterface.OnClickListener(){
            @SuppressLint("ParserError")
			public void onClick (DialogInterface dialog, int whichButton){
            	String filepath = Environment.getExternalStorageDirectory().getPath() + "/" + RecordService.FILE_DIRECTORY;
            	File file = new File(filepath, fileName);
        		
        		if (file.exists()) {
        			file.delete();
        			listDir.remove(position);
        			//notifyDataSetChanged();
        			onResume();
        		}
            }
        })
        .setNegativeButton(R.string.confirm_delete_no, new DialogInterface.OnClickListener(){
            public void onClick (DialogInterface dialog, int whichButton){
                
                
            }
        })
        .show ();
    }
	
	private void sendMail(String fileName)
	{
		Intent sendIntent;

		sendIntent = new Intent(Intent.ACTION_SEND);
		sendIntent.putExtra(Intent.EXTRA_SUBJECT, context.getString(R.string.sendMail_subject));
		sendIntent.putExtra(Intent.EXTRA_TEXT, context.getString(R.string.sendMail_body));
		sendIntent.putExtra(Intent.EXTRA_STREAM, Uri.parse("file://" + Environment.getExternalStorageDirectory().getPath() + "/" + RecordService.FILE_DIRECTORY + "/" + fileName));
		sendIntent.setType("audio/mpeg");

		context.startActivity(Intent.createChooser(sendIntent, context.getString(R.string.send_mail)));
	}
	
	private void startPlayExternal(String charSequence)
	{
		Uri intentUri = Uri.parse("file://" + Environment.getExternalStorageDirectory().getPath() + "/" + RecordService.FILE_DIRECTORY + "/" + charSequence);
		Intent intent = new Intent();
		intent.setAction(Intent.ACTION_VIEW);
		intent.setDataAndType(intentUri, "audio/mpeg");
		context.startActivity(intent);
	}
	
	/**
	 * Fetches list of previous recordings
	 * @param f
	 * @return
	 */
    private List<Model> ListDir2(File f) {
		File[] files = f.listFiles();
		List<Model> fileList = new ArrayList<Model>();
		for (File file : files) {
			fileList.add(new Model(file.getName()));
		}
		
		Collections.sort(fileList);
        Collections.sort(fileList, Collections.reverseOrder());

		return fileList;
	}
}